package com.rzico.quartz.listener;

import com.rzico.core.entity.SysJob;
import com.rzico.core.service.SysJobService;
import com.rzico.quartz.job.JobTask;
import com.rzico.util.IPUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.net.InetAddress;
import java.util.List;


/**
 * @author zhongzm
 * @date 2020/2/2
 * 启动数据库中已经设定为 启动状态(status:1)的任务 项目启动时init
 */

@Configuration
@Slf4j
public class DataSourceJobThread extends Thread {

    @Autowired
    SysJobService sysJobService;

    @Autowired
    protected JobTask jobTask;

    @Override
    public void run() {
        try {
            log.info("----------任务线程启动---------");
            SysJob job = new SysJob();
            job.setStatus(1);
            job.setExecAddr(IPUtils.getLocalIp());//1
            List<SysJob> jobList = sysJobService.select(job);
            jobList.forEach(jobs -> {
                       if (jobs.getExecAddr()!=null && jobs.getExecAddr().equals(IPUtils.getLocalIp())) {
                            log.info("---任务[" + jobs.getId() + "," + jobs.getName() + "]系统 init--开始启动---------");
                            jobTask.startJob(jobs);
                       }
                    }
            );
            if (jobList.size() == 0) {
                log.info("---数据库暂无启动的任务---------");
            } else {
                log.info("---任务启动完毕---------");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
